import pandas as pd
from pymongo import MongoClient


def import_excel_to_mongodb(excel_file_path, db_name, collection_name, columns_to_str):
    try:
        # 读取 Excel 文件
        df = pd.read_excel(excel_file_path, dtype={col: str for col in columns_to_str})
        # 将 DataFrame 转换为字典列表
        data = df.to_dict(orient='records')

        # 连接到 MongoDB
        # client = MongoClient('mongodb://root:xinkao%402021@124.71.235.241:27042/admin?directConnection=true')  # 测试环境
        client = MongoClient('mongodb://127.0.0.1:27017/')  # 测试环境

        # 测试连接
        client.admin.command('ping')
        print("✅ 成功连接到 MongoDB 集群!")

        # 选择数据库
        db = client[db_name]
        # 选择 collection
        collection = db[collection_name]

        # 插入数据到 collection
        result = collection.insert_many(data)
        print(f"成功插入 {len(result.inserted_ids)} 条记录。")

    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        if 'client' in locals():
            client.close()


# 使用示例
excel_file_path = 'D:\\需求\\市平台项目\\真正导入部门.xlsx'
db_name = 'cloud_campus_test1_20240108'
collection_name = 'school_organization'
# 指定需要作为字符串处理的列名
columns_to_str = ['_id','schoolId','parentOrg','parentList']
import_excel_to_mongodb(excel_file_path, db_name, collection_name,columns_to_str)
